<?php

namespace App\Api\Controllers;

use App\Models\Commodity;
use App\Models\Order;
use App\Models\SearchLog;
use App\Models\User;
use App\Api\Requests\UserRequest;
use Dingo\Api\Http\Request;
use App\Models\UserLog;
use Illuminate\Support\Facades\DB;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class UsersController extends Controller
{
    //绑定比特币地址
    public function bind_btc_address(Request $request){
        $user = $this->user();
        if(!$request->btc_address)
            return $this->error('请输入比特币地址');
        $user->fill($request->only(['btc_address']));
        $user->save();
        return $this->success($user);
    }
    //获取用户团队
    public function team(Request $request){
        if($request->id){
            $user = User::find($request->id);
        }else{
            $user = $this->user();
        }
        return $this->success($user->team()->orderBy('sort','desc')->get());
    }

    //金额变动记录
//    public function user_log(Request $request){
//        $where = [];
//        if($request->currency_type)
//            $where['currency_type'] = $request->currency_type;
//        if($request->type)
//            $where['type'] = $request->type;
//        return $this->success($this->user()->user_log()->where($where)->orderBy('id','desc')->get());
//    }

    public function user_log(Request $request){
        $where = [];
        if($request->currency_type && $request->type != 53) {
            $where['currency_type'] = $request->currency_type;
        }
        if($request->type) {
            $where['type'] = $request->type;
        }
        $query = $this->user()->user_log()->where($where)->orderBy('id','desc');
        if($request->starttime && $request->endtime){
            $query = $this->user()->user_log()->where($where)->where('created_at','>',$request->starttime)->where('created_at','<',$request->endtime)->orderBy('id','desc');
        }
        $res1 = $query->get();
        $res['in'] = $query->sum('in');
        $res['out'] = $query->sum('out');
        $res['data'] = $res1;
        return $this->success($res);
    }
    //实名认证
    public function real_verified(Request $request){
        $user = $this->user();
        if($user->is_real == 1)
            return $this->error('已实名认证');
        if(!$request->real_name)
            return $this->error('请输入真实姓名');
        if(!$request->id_number)
            return $this->error('请输入身份证号');
        if(!$request->bank_card)
            return $this->error('请输入银行卡号');
        if(!$request->bank_name)
            return $this->error('请输入银行名称');
        $user->fill($request->only(['real_name','id_number','bank_card','bank_name']));
        $user->is_real = 1;
        $user->save();
        return $this->success($user);
    }

    /**
     * 用户个人资料
     * @return \Dingo\Api\Http\Response
     */
    public function me()
    {
        $user = $this->user();
//        $date = date("Y-m-d",strtotime("-1 day"));
//        $yes_btc = $userLog->where('type',42)->where('currency_type','=','btc')->where('created_at','>',$date.' 00:00:00')->where('created_at','<',$date.' 23:59:59')->where('user_id',$user->id)->sum('in');
//        $yes_back_btc = $userLog->where('type',45)->where('currency_type','=','btc')->where('created_at','>',$date.' 00:00:00')->where('created_at','<',$date.' 23:59:59')->where('user_id',$user->id)->sum('out');
//        $total_btc = $userLog->where('type',42)->where('currency_type','=','btc')->where('user_id',$user->id)->sum('in');
//        $total_back_btc = $userLog->where('type',45)->where('currency_type','=','btc')->where('user_id',$user->id)->sum('out');
//        $total_computing = Order::where('user_id',$user->id)->where('status',1)->sum('computing');
//        $total_electricity_fee = '-'.Order::where('user_id',$user->id)->where('status',1)->sum('total_electricity_fee');
//        $user->yes_btc = bcsub($yes_btc,$yes_back_btc,10);
//        $user->total_btc = bcsub($total_btc,$total_back_btc,10);
//        $user->total_computing = $total_computing;
//        $user->total_electricity_fee = abs($total_electricity_fee);
        return $this->success($user);
    }

    /**
     * 找回密码
     * @param UserRequest $request
     */
    public function retrieve_password(UserRequest $request){
        $verifyData = \Cache::get($request->verification_key);

        if (!$verifyData) {
            return $this->error('验证码已失效');
        }

        if ($verifyData['code'] != $request->verification_code) {
            return $this->error('验证码错误');
        }

        //判断用户是否存在
        $user = User::where(['mobile'=>$verifyData['mobile']])->first();
        if(!$user){
            return $this->error('该手机号未注册');
        }
        $user->password = bcrypt($request->password);
        $user->save();
        return $this->success();
    }

    /**
     * 用户注册
     * @param UserRequest $request
     * @return mixed
     */
    public function store(UserRequest $request)
    {
        $verifyData = \Cache::get($request->verification_key);

        if (!$verifyData) {
            return $this->error('验证码已失效');
        }

        if ($verifyData['code'] != $request->verification_code) {
            return $this->error('验证码错误');
        }

        //判断用户是否存在
        if(User::where(['mobile'=>$verifyData['mobile']])->first()){
            return $this->error1('该手机号已注册');
        }

        $user = [
            'username' => $verifyData['mobile'],
            'mobile' => $verifyData['mobile'],
            'password' => bcrypt($request->password),
        ];

        //判断邀请码
        if($request->invitation_code){
            //$puser = User::where(['id'=>$request->invitation_code])->first();
            $puser = $request->invitation_code;
            $user['pid'] = $puser ? $puser : 0;
        }

        User::create($user);

        // 清除验证码缓存
        //\Cache::forget($request->verification_key);

        return $this->success(['message'=>'注册成功']);
    }

    public function update(UserRequest $request)
    {
        $user = $this->user();
        $attributes = $request->only(['username']);
        $user->update($attributes);

        return $this->success(['message'=>'修改成功']);
    }

    public function invite(Request $request)
    {
        $user = $this->user();
        $pid = $request->only(['pid']);
        $user->update($pid);

        return $this->success(['message'=>'邀请成功']);
    }

    public function qrcode(){
        $id = $this->user()->id;
        $name = date("YmdHis").rand(1000,999);
        QrCode::format('png')->size(200)->generate(config('host_name').'?id='.$id,'../public/uploads/images/'.$name.'.png');
        $this->user()->update(['qrcode'=>'uploads/images/'.$name.'.png']);
        //return $this->success(['message'=>'uploads/images/'.$name.'.png']);
        return $this->success('uploads/images/'.$name.'.png');
    }

    public function search(Request $request){
        $id = $this->user()->id;
        $name = $request->input('name');
        $label = $request->input('label');
        if(!empty($name)) {
            $res = Commodity::where('name', 'like', "%$name%")->where('status', 1)->get();
            $search = new SearchLog();
            $search->user_id = $id;
            $search->name = $name;
            $search->save();
        }
        if(!empty($label)) {
            $res = Commodity::where('label',$label)->where('status', 1)->get();
        }
        return $this->success($res);
    }

    public function search_round(Request $request){
        $lat = $request->input('lat');
        $lon = $request->input('lon');
//        $sql='select * from machines where lat > '.$lat.'-0.5 and lat < '.$lat.'+0.5 and lng > '.$lon.'-0.5 and lng < '.$lon.'+0.5 order by ACOS(SIN(('.$lat.' * 3.1415) / 180 ) *SIN((lat * 3.1415) / 180 ) +COS(('.$lat.' * 3.1415) / 180 ) * COS((lat * 3.1415) / 180 ) *COS(('.$lon.'* 3.1415) / 180 - (lng * 3.1415) / 180 ) ) * 6380 asc limit 10';
        $sql = "SELECT * FROM machines WHERE (ACOS(SIN(($lat*3.1415)/180) * SIN((lat*3.1415)/180) + COS(($lat*3.1415)/180) * COS((lat*3.1415)/180) * COS(($lon*3.1415)/180 - (lng*3.1415)/180))*6370.996)<=10";
        $res = DB::select($sql);
        return $this->success($res);
    }
}